package com.newland.flow.Controller
{
	import com.anotherflexdev.diagrammer.Link;
	import com.anotherflexdev.diagrammer.NodeContextPanel;
	import com.newland.flow.effect.EffectUtil;
	import com.newland.flow.model.LinkModel;
	import com.newland.flow.model.NodeModel;
	import com.newland.flow.model.NodeUtils;
	import com.newland.flow.view.BaseNodeView;
	import com.newland.flow.view.EndNodeView;
	import com.newland.flow.view.LinkLineView;
	import com.newland.flow.view.LinkNodeView;
	import com.newland.flow.view.StartNodeView;
	import com.newland.flow.view.TaskNodeView;
	
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import mx.collections.ArrayCollection;
	import mx.containers.Canvas;
	import mx.controls.Alert;
	import mx.core.Container;
	import mx.core.DragSource;
	import mx.core.UIComponent;
	import mx.effects.Glow;
	import mx.events.DragEvent;
	import mx.managers.DragManager;
	
	public class Controller
	{
		/**
		 * 节点选择单击动作
		 **/
		private static var lastClickNode:UIComponent = null;
		
		[Embed('asserts/figures/start.gif')]
		[Bindable]
		private static var startIcon:Class;
		
		[Embed('asserts/figures/activity.gif')]
		[Bindable]
		private static var taskIcon:Class;
		
		[Embed('asserts/figures/end.gif')]
		[Bindable]
		private static var endIcon:Class;
		
		[Bindable]
		//当前节点类型标识
		private static var nodeType:String;
		//新建节点
		private static var createNode:UIComponent = null;
		//流程节点集合
		private static var nodeCollection:ArrayCollection = new ArrayCollection;
		//流程连接线集合
		private static var lineCollection:ArrayCollection = new ArrayCollection;
		//该对象为存储两个需要连线的节点对象结合；长度仅为2；当达到的时候，将两个对象画线
		private static var linkObjectCollection:ArrayCollection = new ArrayCollection();
		//选择的连接线对象
		private static var clickLinkLine:LinkLineView;
		//效果
		private static var effect:EffectUtil = new EffectUtil();
		
		/**
		 * “节点选择”栏中节点选择的动作
		 **/
		public static function onClick(event:MouseEvent):void
		{
			if(linkObjectCollection.length > 0) {
				for(var i:Number=0;i<linkObjectCollection.length;i++) {
					UIComponent(linkObjectCollection.getItemAt(i)).clearStyle("backgroundColor");
				}
				linkObjectCollection.removeAll();//确保彻底清除临时链接对象集
			}
			var node:UIComponent = event.currentTarget as UIComponent;
			/**通过两次点击对象的isClicked判断**/
			if(!BaseNodeView(node).isClicked) {//按下效果
				BaseNodeView(node).isClicked = true;
				node.setStyle("backgroundColor","#9adae8");
				node.removeEventListener(MouseEvent.ROLL_OUT,rollOut);
				node.removeEventListener(MouseEvent.ROLL_OVER,rollOver);
				/**根据触发不同动作的组件，设置不同的响应**/
				if(node is StartNodeView) {
					nodeType = NodeUtils.STARTNODE;
				}
				if(node is TaskNodeView) {
					nodeType = NodeUtils.TASKNODE;
				}
				if(node is EndNodeView) {
					nodeType = NodeUtils.ENDNODE;
				}
				if(node is LinkNodeView) {
					nodeType = NodeUtils.LINKLINE;
				}
				//释放上次点击按键的设置
				if(lastClickNode != null) {
					BaseNodeView(lastClickNode).isClicked = false;
					lastClickNode.setStyle("backgroundColor","#ffffff");
					lastClickNode.addEventListener(MouseEvent.ROLL_OVER,rollOver);
					lastClickNode.addEventListener(MouseEvent.ROLL_OUT,rollOut);
				}
				lastClickNode = event.currentTarget as UIComponent;
			} else {//再次按下效果
				BaseNodeView(node).isClicked = false;
				node.setStyle("backgroundColor","#ffffff");
				node.addEventListener(MouseEvent.ROLL_OVER,rollOver);
				node.addEventListener(MouseEvent.ROLL_OUT,rollOut);
				lastClickNode = null;
				nodeType = "";
			}
		}
		/**
		 * 节点选择鼠标移入效果
		 **/
		public static function rollOver(event:MouseEvent):void
		{
			var target:UIComponent = event.currentTarget as UIComponent;
			target.setStyle("backgroundColor","#9adae8");
		}
		/**
		 * 节点选择鼠标移出效果
		 **/
		public static function rollOut(event:MouseEvent):void
		{
			var target:UIComponent = event.currentTarget as UIComponent;
			target.setStyle("backgroundColor","#ffffff");
		}
		
		public static function designClick(event:MouseEvent):void
		{
			var target:UIComponent = event.currentTarget as UIComponent;
			var createNode:UIComponent;
			if(nodeType !=null && nodeType != "") {
				if(nodeType == NodeUtils.LINKLINE) {
					/**
					 * 选择两个节点，进行画线
					 * 只有两次都点击在Node节点上，才进行画线操作；
					 * 设置鼠标样式为画线形状
					 **/
					
				} else {
					if(nodeType == NodeUtils.STARTNODE) {
						if(nodeCollection != null && nodeCollection.length > 0) {
							for(var i:Number=0;i<nodeCollection.length;i++) {
								var obj:UIComponent = nodeCollection.getItemAt(i) as UIComponent;
								if(BaseNodeView(obj) is StartNodeView) {
									return;
								}
							}
						}
						var startNode:StartNodeView = new StartNodeView(startIcon,NodeUtils.START_NODE_NAME);
						startNode.nodeType = NodeUtils.STARTNODE;
						createNode = startNode as UIComponent;
					}
					if(nodeType == NodeUtils.TASKNODE) {
						var taskNode:TaskNodeView = new TaskNodeView(taskIcon,NodeUtils.TASK_NODE_NAME);
						taskNode.nodeType = NodeUtils.TASKNODE;
						createNode = taskNode as UIComponent;
					}
					if(nodeType == NodeUtils.ENDNODE) {
						if(nodeCollection != null && nodeCollection.length > 0) {
							for(var j:Number=0;j<nodeCollection.length;j++) {
								var obj:UIComponent = nodeCollection.getItemAt(j) as UIComponent;
								if(BaseNodeView(obj) is EndNodeView) {
									return;
								}
							}
						}
						var endNode:EndNodeView = new EndNodeView(endIcon,NodeUtils.END_NODE_NAME);
						endNode.nodeType = NodeUtils.ENDNODE;
						createNode = endNode as UIComponent;
					}
					createNode.addEventListener(MouseEvent.CLICK,nodeClick);
					createNode.addEventListener(MouseEvent.MOUSE_MOVE,node_mouseMoveHandler);
					createNode.removeEventListener(MouseEvent.ROLL_OUT,rollOut);
					createNode.removeEventListener(MouseEvent.ROLL_OVER,rollOver);
					createNode.addEventListener(MouseEvent.ROLL_OUT,rollOutEffect);
					createNode.addEventListener(MouseEvent.ROLL_OVER,rollOverEffect);
					createNode.useHandCursor = true;
					createNode.buttonMode = true;
					createNode.x = target.mouseX;
					createNode.y = target.mouseY;
					target.addChild(createNode);
					//组件集合管理
					/*
					var model:NodeModel = new NodeModel();
					if(createNode is StartNodeView) {
						model.nodeType = NodeUtils.STARTNODE;
						model.nodeName = NodeUtils.START_NODE_NAME;
					}
					if(createNode is TaskNodeView) {
						model.nodeType = NodeUtils.TASKNODE;
						model.nodeName = NodeUtils.TASK_NODE_NAME;
					}
					if(createNode is EndNodeView) {
						model.nodeType = NodeUtils.ENDNODE;
						model.nodeName = NodeUtils.END_NODE_NAME;
					}
					model.x = target.mouseX;
					model.y = target.mouseY;
					*/
					nodeCollection.addItem(createNode);
				}
			}
		}
		/**
		 * 节点双击事件
		 * 该对象为存储两个需要连线的节点对象结合；长度仅为2；当达到的时候，将两个对象画线
		 **/
		private static function nodeClick(event:MouseEvent):void
		{
			/**
			 * 弹出属性设置框
			 * 当锁定状态为画线时，点击节点的时候，不触发获取属性的动作
			 **/
			if(nodeType == NodeUtils.LINKLINE)
			{
				var clickObject:UIComponent = event.currentTarget as UIComponent;
				//clickObject.setStyle("borderColor","0x0000ff");//表框颜色，标识选中的节点对象
				BaseNodeView(clickObject).setStyle("backgroundColor","0x0000ff");//表框颜色，标识选中的节点对象
				linkObjectCollection.addItem(clickObject);
				/**
				 * 在进行画线前，还需要进行判断
				 * 1、连线不能从任务节点到开始节点；
				 * 2、不能从结束节点到开始节点
				 * 3、不能从结束节点到任务节点
				 * 4、在已经存在有连接线的两个任务节点，再次连线
				 * 5、在已经存在有连接线的两个任务节点，再次做相反的连接
				 * 6、连接的两个节点为自身（同一对象）的时候，提示不予连接
				 **/
				if(linkObjectCollection.length == 2)
				{
					var startNode:UIComponent = linkObjectCollection.getItemAt(0) as UIComponent;
					var endNode:UIComponent = linkObjectCollection.getItemAt(1) as UIComponent;
					/**1\2\3情况的判断**/
					if((startNode is TaskNodeView && endNode is StartNodeView)
						|| (startNode is EndNodeView && endNode is StartNodeView) 
						|| (startNode is EndNodeView && endNode is TaskNodeView)) {
						startNode.clearStyle("backgroundColor");
						endNode.clearStyle("backgroundColor");
						linkObjectCollection.removeAll();//移除临时对象
						Alert.show(NodeUtils.ERROR_LINE_TIP);
						return;
					}
					/**4\5 情况的判断**/
					if(lineCollection != null && lineCollection.length > 0) {
						for(var index:Number=0;index<lineCollection.length;index++) {
							var link:LinkModel = lineCollection.getItemAt(index) as LinkModel;
							var sNode:UIComponent = link.preNode;
							var eNode:UIComponent = link.endNode;
							if((sNode == startNode && eNode == endNode) || (sNode == endNode && eNode == startNode)) {
								startNode.clearStyle("backgroundColor");
								endNode.clearStyle("backgroundColor");
								linkObjectCollection.removeAll();//移除临时对象
								Alert.show(NodeUtils.HAD_LINE_TIP);
								return;
							}
						}
					}
					/**6 情况的判断**/
					if(startNode == endNode) {
						startNode.clearStyle("backgroundColor");
						endNode.clearStyle("backgroundColor");
						linkObjectCollection.removeAll();//移除临时对象
						return;
					}
					var linkLine:LinkLineView = new LinkLineView();
					linkLine.setStartPoint(new Point(startNode.x+startNode.width/2,startNode.y+startNode.height/2));
					linkLine.setEndPoint(new Point(endNode.x+endNode.width/2,endNode.y+endNode.height/2));
					linkLine.drawLine();
					(startNode.parentDocument.design as UIComponent).addChild(linkLine);
					/**1、通过LinkModel维护开始节点、结束节点的连接关系**/
					var model:LinkModel = new LinkModel();
					model.preNode = startNode;
					model.line = linkLine;
					model.endNode = endNode;
					/**2、在开始节点中，维护它所指向的下一节点关系**/
					if(nodeCollection.contains(startNode)) {
						var index:Number = nodeCollection.getItemIndex(startNode);
						var node:BaseNodeView = nodeCollection.getItemAt(index) as BaseNodeView;
						node.linkToCollection.addItem(endNode);
					}
					//连接完毕，清除选中节点的底色
					startNode.clearStyle("backgroundColor");
					endNode.clearStyle("backgroundColor");
					lineCollection.addItem(model);//将开始节点、线、结束节点关系放入连接线模型维护
					linkObjectCollection.removeAll();//移除临时对象
				}
			} else {
				Alert.show("节点属性");
			}
		}
		//对象拖拽的完整流程
		private static function node_mouseMoveHandler(event:MouseEvent):void
		{
			var dragInitiator:UIComponent = event.currentTarget as UIComponent;
			var ds:DragSource = new DragSource();
			ds.addData(dragInitiator,"Component");
			DragManager.doDrag(dragInitiator,ds,event);
		}
		public static function design_dragEnterHandler(event:DragEvent):void
		{
			if(event.dragSource.hasFormat("Component"))
			{
				DragManager.acceptDragDrop(event.currentTarget as UIComponent);
			}
		}
		/**
		 * 移动对象位置确定后，根据开始节点、连接线、结束节点关系集合，重绘连接线
		 **/
		public static function design_dragDropHandler(event:DragEvent):void
		{
			var dragObject:UIComponent = event.dragInitiator as UIComponent;
			dragObject.x = Container(event.currentTarget).mouseX - dragObject.width/2;
			dragObject.y = Container(event.currentTarget).mouseY - dragObject.height/2;
			if(dragObject.parent!=event.currentTarget){
				Container(event.currentTarget).addChild(dragObject);
			}
			refresh(dragObject);//移动节点，重绘连接线
		}
		private static function refresh(dragObject:UIComponent):void
		{
			if(lineCollection.length > 0)
			{
				for(var i:Number=0;i<lineCollection.length;i++)
				{
					var model:LinkModel = lineCollection.getItemAt(i) as LinkModel;
					var lineView:LinkLineView = model.line as LinkLineView;
					if(model.preNode == dragObject)
					{
						lineView.removeLine();
						lineView.setStartPoint(new Point(dragObject.x+dragObject.width/2,dragObject.y+dragObject.height/2));
						lineView.drawLine();
					}
					if(model.endNode == dragObject)
					{
						lineView.removeLine();
						lineView.setEndPoint(new Point(dragObject.x+dragObject.width/2,dragObject.y+dragObject.height/2));
						lineView.drawLine();
					}
				}
			}
		}
		/**
		 * 节点鼠标移入、移除效果
		 **/
		private static function rollOutEffect(event:MouseEvent):void {
			effect.rollOutEffect(event,[event.currentTarget]);
		}
		private static function rollOverEffect(event:MouseEvent):void {
			effect.rollOverEffect(event,[event.currentTarget]);
		}
		/**连接线动作事件**/
		public static function lineOnClick(event:Event):void {
			var line:LinkLineView = event.currentTarget as LinkLineView;
			if(clickLinkLine !=null && clickLinkLine == line) {//两次点击同一对象，取消选择
				clickLinkLine.setLineColor(0x000000);
				clickLinkLine.drawLine();
				clickLinkLine = null;
			}
			if(clickLinkLine !=null && clickLinkLine != line) {//选择两个不同对象；以第二次点击对象为准；第一次点击对象取消选中状态
				clickLinkLine.setLineColor(0x000000);
				clickLinkLine.drawLine();
				line.setLineColor(0xFF0000);
				line.drawLine();
				clickLinkLine = line;
			} else {
				line.setLineColor(0xFF0000);
				line.drawLine();
				clickLinkLine = line;
			}
		}
		public static function lineRollOver(event:MouseEvent):void {
			effect.rollOverEffect(event,[event.currentTarget]);
		}
		public static function lineRollOut(event:MouseEvent):void {
			effect.rollOutEffect(event,[event.currentTarget]);
		}
		
		/**工具栏动作**/
		public static function saveHandler(event:MouseEvent):void {
			var modelCollection:ArrayCollection = new ArrayCollection();
			if(nodeCollection != null && nodeCollection.length >0) {
				for(var n:Number=0;n<nodeCollection.length;n++) {
					var node:BaseNodeView = nodeCollection.getItemAt(n) as BaseNodeView;
					var model:NodeModel = new NodeModel();
					model.id = node.id;
					model.nodeName = node.nodeName;
					model.x = node.x;
					model.y = node.y;
					model.nodeType = node.nodeType;
					if(node.linkToCollection!=null && node.linkToCollection.length>0) {
						for(var m:Number=0;m<node.linkToCollection.length;m++) {
							model.nextNodes.addItem(UIComponent(node.linkToCollection.getItemAt(m)).id);
						}
					}
					modelCollection.addItem(model);
				}
			}
		}
	}
}